<?php

class Tarea_IndexController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    // ver todas las tareas
    public function viewAction() {
        $row = new Tarea_Model_DbTable_Tarea();
        $select = $row->select()->setIntegrityCheck(false)
                ->from(array('t' => 'tarea'), array('tarea_id' => 'id', 'title', 'status'))
                ->join(array('o' => 'orden'), 'o.id = t.id_orden', array('code'))->group('t.id')
                ->join(array('oj' => 'orden_job'), 'oj.id_orden = o.id');
        $result = $row->fetchAll($select);
        $this->view->result = $result;
    }

    //todas las tarea pertencientes al usuario en sesion *//////////////////
    public function mytaskAction() {
        $auth = Zend_Auth::getInstance();
        $user = $auth->getIdentity()->id;
        $row = new Tarea_Model_DbTable_Tarea();

        $select = $row->select()->setIntegrityCheck(false)
                ->from(array('t' => 'tarea'), array('*'))
                ->join(array('tu' => 'tarea_user'), 't.id = tu.id_tarea')
                ->join(array('u' => 'user'), 'tu.id_user = u.id and u.id = ' . $user)
                ->where('t.status!=?', 5); //que omita las tareas aprobadas

        $result = $row->fetchAll($select);
        $this->view->result = $result;
    }

    // ver una sola tarea debe tener un id en la url ////////////////////
    public function viewtareaAction() {
        $id = $this->_getParam('id', 0);

        if (!is_numeric($id) or $id <= 0) {
            $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Solicitud no valida.');
            $this->_helper->redirector->gotoUrlAndExit('/tarea/index/view');
        }
        $tarea = new Tarea_Model_DbTable_Tarea();
        if ($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getParams();
            $tarea->update(array('status' => $data['status']), "id = '$id'");
            $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Cambio de estado exitoso.');
            $this->_helper->redirector->gotoUrlAndExit('/tarea/index/view');
        }
        $rowTarea = $tarea->fetchRow("id = '$id'");
        $this->view->tarea = $rowTarea;
        $ordenDb = new Orden_Model_DbTable_Orden();
        $tareaUser = new Tarea_Model_DbTable_TareaUser();

        $this->view->resTareaUser = $tareaUser->fetchAll('id_tarea=' . $id);
        $this->view->orden = $ordenDb->fetchRow('id=' . $rowTarea->id_orden);
    }

    public function deleteAction() {
        $id = $this->_getParam('id', 0);
        $tarea = new Tarea_Model_DbTable_Tarea();
        $tarea->remove((int) $id);

        $tareaUser = new Tarea_Model_DbTable_TareaUser();
        $tareaUser->delete('id_tarea=' . $id);

        $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Tarea eliminada con exito.');
        $this->_helper->redirector->gotoUrlAndExit('/tarea/index/view');
    }

    public function addtareaAction() {
        $id_orden = $this->_getParam('id', 0);
        $ordenTrabajo = new Orden_Model_DbTable_OrdenJob();
        if ($this->getRequest()->isPost()) {

            $auth = Zend_Auth::getInstance();
            $iduser = $auth->getIdentity()->id;
            $data = $this->getRequest()->getParams();

            $dataTemp = array();
            $tareaDb = new Tarea_Model_DbTable_Tarea();

            $dataTemp['id_user_create'] = $iduser;
            $dataTemp['title'] = $data['title'];
            $dataTemp['description'] = $data['description'];
            $dataTemp['id_orden'] = $data['id_orden'];
            $dataTemp['id_job'] = $data['id_job'];
            $dataTemp['status'] = 1;
            $x = $tareaDb->insert($dataTemp);

            if ($x != null) {
                $tareaUser = new Tarea_Model_DbTable_TareaUser();
                foreach ($data['checkUser'] as $user) {
                    $tareaUser->insert(array('id_tarea' => $x, 'id_user' => $user));
                }
                /// send email add tarea
                $sendEmailTask = new Amz_Resource_SendEmailTask();
                $sendEmailTask->sendEmailTask($data['id_orden'], $x, 'ADD_TASK');
            }
            $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Tarea adicionada con exito.');
            $this->_helper->redirector->gotoUrlAndExit('/tarea/index/addtarea/id/' . $x);
        } else {
            $ordenDb = new Orden_Model_DbTable_Orden();
            if ($id_orden > 0) {
                $this->view->id_orden = $id_orden;
                $row = $ordenDb->fetchRow('id=' . $id_orden);
                $this->view->title_task = 'para la Orden "' . $row->code . ' - ' . $row->title . '"';
                $this->view->resultJob = $ordenTrabajo->fetchAll('id_orden='.$id_orden);
            } else {
                $this->view->resultOrden = $ordenDb->fetchAll();
                $this->view->id_orden = 0;
            }
            $userDb = new User_Model_DbTable_User();
            $this->view->resultUserSupervisores = $userDb->fetchAll('estado=1 and type="DEPARTAMENT" and idgroup=13');
            $this->view->resultUserDesignerDeveloper = $userDb->fetchAll('estado=1 and type="DEPARTAMENT" and idgroup=14');
        }
    }

    public function editAction() {
        $id = $this->_getParam('id', 0);
        $tareaDb = new Tarea_Model_DbTable_Tarea();
        $tareaUser = new Tarea_Model_DbTable_TareaUser();
        $ordenTrabajo = new Orden_Model_DbTable_OrdenJob();
        if ($this->getRequest()->isPost()) {

            $auth = Zend_Auth::getInstance();
            $iduser = $auth->getIdentity()->id;
            $data = $this->getRequest()->getParams();

            $dataTemp = array();
            $dataTemp['id_user_create'] = $iduser;
            $dataTemp['title'] = $data['title'];
            $dataTemp['description'] = $data['description'];
            $dataTemp['id_orden'] = $data['id_orden'];
            $dataTemp['id_job'] = $data['id_job'];
            $dataTemp['status'] = 1;
            $tareaDb->update($dataTemp, 'id=' . $data['id']);

            $tareaUser->delete('id_tarea=' . $data['id']);
            foreach ($data['checkUser'] as $user) {
                $tareaUser->insert(array('id_tarea' => $data['id'], 'id_user' => $user));
            }

            /// send email add tarea
            $sendEmailTask = new Amz_Resource_SendEmailTask();
            $sendEmailTask->sendEmailTask($data['id_orden'], $id, 'EDIT_TASK');

            $this->_helper->FlashMessenger()->setNamespace('success')->addMessage('Tarea editada con exito.');
            $this->_helper->redirector->gotoUrlAndExit('/tarea/index/edit/id/' . $data['id']);
        } else {
            $rowTarea = $tareaDb->fetchRow("id=" . $id);
            $this->view->tarea = $rowTarea;

            $ordenDb = new Orden_Model_DbTable_Orden();
            $this->view->resultOrden = $ordenDb->fetchAll('status != 5'); //las que no estan aprobadas

            $this->view->usersTarea = $tareaUser->fetchAll('id_tarea=' . $id);

            $this->view->resultJob = $ordenTrabajo->fetchAll('id_orden='.$rowTarea->id_orden);
            
            $userDb = new User_Model_DbTable_User();
            $this->view->resultUserSupervisores = $userDb->fetchAll('estado=1 and type="DEPARTAMENT" and idgroup=13');
            $this->view->resultUserDesignerDeveloper = $userDb->fetchAll('estado=1 and type="DEPARTAMENT" and idgroup=14');
        }
    }

    function es_int($numero) {
        if (preg_match("/^(+|-)?[0-9]+$/", $numero))
            return true;
        else
            return false;
    }
    
    public function getJobsAction(){
        $ordenJob = new Orden_Model_DbTable_OrdenJob();
        $request = $this->getRequest();
        
        if($request->isXmlHttpRequest()){
            $idOrden = $request->getParam('id_orden', 0);
            $result = $ordenJob->fetchAll('id_orden = '.$idOrden);
            $jsonData = Zend_Json::encode($result->toArray());
            echo $jsonData;
            exit;
        }
    }
}

?>
